package com.billow.control
{
	import com.billow.utils.Zip;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	public class UpdateControl
	{
		private var _fc:FileControl = new FileControl();
		private var _zip:Zip;
		private var _totalNum:int;
		private var _installNum:int;
		private var _callback:Function;
		private var _saveDirectory:File;
		
		public function UpdateControl()
		{
			
		}
		
		/** 已安装 */
		public function get totalNum():int {return _totalNum;}
		
		/** 全部 */
		public function get installNum():int {return _installNum;}
		
		
		/**
		 * 安装更新文件  
		 * @param zipFile 文件必须是 zip
		 * @param saveDirectory 保存目标文件夹
		 * @param callback 返回函数
		 * 
		 */		
		public function install(zipFile:File ,saveDirectory:File ,callback:Function):void
		{
			_installNum = 0;
			_totalNum = 0;
			_saveDirectory = saveDirectory;
			_callback = callback;
			removeZip();
			_zip = new Zip();
			_zip.addEventListener(IOErrorEvent.IO_ERROR ,onError);
			_zip.addEventListener(Event.COMPLETE, onComplete);
			_zip.loadBytes(_fc.readBytes(zipFile));
		}
		
		
		/** Error */
		private function onError(event:IOErrorEvent):void
		{
			trace("zip error");
		}
		
		/** Complete */
		private function onComplete(event:Event):void
		{
			_installNum = 0;
			_totalNum = _zip.getFileCount();
			onInstall();
		}
		
		/** 安装处理 */
		private function onInstall():void
		{
			try{
				if(_zip.getFileAt(_installNum).content.length>0)
				{
					var file:File = new File(_saveDirectory.resolvePath(_zip.getFileAt(_installNum).filename).nativePath);
					_fc.saveFile(file ,_zip.getFileAt(_installNum).content);
					_zip.getFileAt(_installNum).content.clear();
				}
			}catch(e:Error){
				trace("第"+_installNum+"个文件安装失败" ,e.message);
			}
			
			
			_installNum++;
			if(_installNum<_totalNum)
			{
				setTimeout(onInstall ,50);
			}else{
				removeZip();
			}
			
			//trace(_installNum+"/"+_totalNum);
			_callback();
		}
		
		
		
		/** 清除 ZIP */	
		private function removeZip():void
		{
			if(_zip!=null)
			{
				_zip.removeEventListener(IOErrorEvent.IO_ERROR ,onError);
				_zip.removeEventListener(Event.COMPLETE, onComplete);
				_zip.close();
				_zip = null;
			}
			
			BSystem.gc();
		}
		
		
		
		/**
		 * 回收 
		 * 
		 */		
		public function dispose():void
		{
			_saveDirectory = null;
			if(_fc!=null)
			{
				_fc.dispose();
				_fc = null;
			}
			removeZip();
		}
	}
}